﻿using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CoreLibs;
using HUGATE.Utility;
using HUGATE.ItemObject;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.ObjectBuilder;
using Telerik.Web.UI;
namespace HUGATE.Item.Controls.Category
{
    /// <summary>
    /// Creator : Nguyễn Đức Hiếu
    /// Date    : 13/12/2010
    /// Desc    : Quản lý Danh mục sản phẩm
    /// </summary>
    public partial class CategoryList : System.Web.UI.UserControl
    {
        #region Variables

        private int iPageSize = 10;
        private string strReturnPage = "";


        #endregion

        #region Properties

        public int PageSize
        {
            get { return iPageSize; }
            set { iPageSize = value; }
        }

        #endregion

        #region Permissions

        //private String strManagerPermission = "ITEM_Category_Manager";
        //private String strSystemPermission = "ITEM_Category_System";

        #endregion

        #region Support Functions

        /// <summary>
        /// Nạp danh sách dữ liệu vào lưới
        /// </summary>
        /// <param name="intPage"></param>
        private void GridDatabind(int intPage)
        {
            ITEMCategory objCategory = new ITEMCategory();
            DataTable dtb = objCategory.SearchData(string.Empty);
            rtvCategory.Nodes.Clear();
            BuildCategoryTree(rtvCategory, dtb, 0);
            Telerik.Web.UI.RadTreeView rtvCategoryInside = rcbCategory.Items[0].FindControl("rtvCategoryInside") as Telerik.Web.UI.RadTreeView;
            rtvCategoryInside.Nodes.Clear();
            BuildCategoryTreeWithRoot(rtvCategoryInside, dtb, 0);            
            rtvCategoryInside.Nodes[0].Selected = true;
            rtvCategoryInside.Nodes[0].Expanded = true;
            //grvObject.DataSource = dtb;
            //grvObject.PageIndex = intPage;
            //grvObject.DataBind();
        }

        private void BuildCategoryTreeWithRoot(Telerik.Web.UI.RadTreeView rtvCategoryInside, DataTable dtb, int parentID)
        {
            Telerik.Web.UI.RadTreeNode root = new Telerik.Web.UI.RadTreeNode("Danh Mục Hàng", "0");
            rtvCategoryInside.Nodes.Add(root);
            DataRow[] drws = dtb.Select("ParentCategoryID=" + parentID);
            foreach (DataRow drw in drws)
            {
                Telerik.Web.UI.RadTreeNode rtn = new Telerik.Web.UI.RadTreeNode(drw["RefCategoryID"].ToString() + " - " + drw["CategoryName"].ToString(), drw["CategoryID"].ToString());
                root.Nodes.Add(rtn);
                BuildCategoryNode(rtn, dtb, Convert.ToInt32(drw["CategoryID"]));
            } 
        }

        private void BuildCategoryTree(Telerik.Web.UI.RadTreeView rtv, DataTable dtb, int parentID)
        {
            DataRow[] drws = dtb.Select("ParentCategoryID=" + parentID);
            foreach (DataRow drw in drws)
            {
                Telerik.Web.UI.RadTreeNode rtn = new Telerik.Web.UI.RadTreeNode(drw["RefCategoryID"].ToString() + " - " + drw["CategoryName"].ToString(), drw["CategoryID"].ToString());
                rtv.Nodes.Add(rtn);
                BuildCategoryNode(rtn, dtb, Convert.ToInt32(drw["CategoryID"]));
            }
        }

        private void BuildCategoryNode(Telerik.Web.UI.RadTreeNode parentNode, DataTable dtb, int parentID)
        {
            DataRow[] drws = dtb.Select("ParentCategoryID=" + parentID);
            foreach (DataRow drw in drws)
            {
                Telerik.Web.UI.RadTreeNode rtn = new Telerik.Web.UI.RadTreeNode(drw["RefCategoryID"].ToString() + " - " + drw["CategoryName"].ToString(), drw["CategoryID"].ToString());
                parentNode.Nodes.Add(rtn);
                BuildCategoryNode(rtn, dtb, Convert.ToInt32(drw["CategoryID"]));
            }
        }
        /// <summary>
        /// Lấy ID của Category con
        /// </summary>
        int IDtemp;
        public int IDDelete(int CurrentID)
        {
            ITEMCategory objCategory = new ITEMCategory();
            DataTable db = objCategory.SearchData("");
            DataRow temp;
            temp = db.Select("CategoryID = " + CurrentID)[0];
            string nodetree = Convert.ToString(temp["NodeTree"]);
            DataRow[] objRows = db.Select("ParentCategoryID = " + CurrentID + "and NodeTree like '%" + nodetree + "%'");
            IDtemp = CurrentID;
            objCategory.CategoryID = IDtemp;
            objCategory.Delete();
            if (objRows != null)
            {
                foreach (DataRow row in objRows)
                {
                    IDtemp = Convert.ToInt32(row["CategoryID"]);
                    objCategory.CategoryID = IDtemp;
                    objCategory.Delete();
                }
            }
            return IDtemp;
        }

        /// <summary>
        /// Fill Data in TreeView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FillTreeview(TreeView tvemp, TreeNode tnParentdNode, int intCurrentID, DataTable dtbl)
        {

            if (tnParentdNode == null)
            {
                tvemp.Nodes.Clear();
                tnParentdNode = new TreeNode();
                tnParentdNode.Text = "Root";
                tnParentdNode.Value = "0";
                tnParentdNode.Expanded = false;
                tvemp.Nodes.Add(tnParentdNode);

            }

            DataRow[] objRows = dtbl.Select("ParentCategoryID = " + intCurrentID.ToString());

            foreach (DataRow row in objRows)
            {
                TreeNode child = new TreeNode();
                child.Text = Convert.ToString(row["CategoryName"]);
                child.Value = Convert.ToString(row["CategoryID"]);
                tnParentdNode.Expanded = false;
                tnParentdNode.ChildNodes.Add(child);
                FillTreeview(tvemp, child, Convert.ToInt32(row["CategoryID"]), dtbl);
            }
        }

        #endregion

        #region Event Functions

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnAddNew.Text = HUGATE.Utility.ResxManager.GetString("Btn_AddNew");
                btnReturn.Text = HUGATE.Utility.ResxManager.GetString("Btn_Return");
                btnSearch.Text = HUGATE.Utility.ResxManager.GetString("Btn_Search");
                btnDelete.Text = HUGATE.Utility.ResxManager.GetString("Btn_Delete");
                btnEdit.Text = HUGATE.Utility.ResxManager.GetString("Btn_Edit");

                grvObject.Columns[0].HeaderText = HUGATE.Utility.ResxManager.GetString("ID") + HUGATE.Utility.ResxManager.GetString("ITEMCategory");
                grvObject.Columns[1].HeaderText = HUGATE.Utility.ResxManager.GetString("Name") + HUGATE.Utility.ResxManager.GetString("ITEMCategory");
                grvObject.Columns[2].HeaderText = HUGATE.Utility.ResxManager.GetString("Description");
                grvObject.Columns[3].HeaderText = HUGATE.Utility.ResxManager.GetString("Level") + " " + HUGATE.Utility.ResxManager.GetString("ITEMCategory");
                grvObject.Columns[4].HeaderText = HUGATE.Utility.ResxManager.GetString("NodeTree");
                grvObject.Columns[5].HeaderText = HUGATE.Utility.ResxManager.GetString("NodeTree");
                grvObject.Columns[6].HeaderText = HUGATE.Utility.ResxManager.GetString("Default");
                grvObject.Columns[7].HeaderText = HUGATE.Utility.ResxManager.GetString("Actived");
                //grvObject.Columns[5].HeaderText =HUGATE.Utility.ResxManager.GetString("System");

                ITEMCategory objCategory = new ITEMCategory();
                DataTable dtb = objCategory.SearchData(string.Empty);
                rtvCategory.Nodes.Clear();
                BuildCategoryTreeWithRoot(rtvCategory, dtb, 0);
                
                grvObject.EmptyDataText = string.Format(ResxManager.GetString("DetailItemNotFound"), HUGATE.Utility.ResxManager.GetString("ITEMCategory", true));

                GridDatabind(0);

            }
            ctrlCategoryEdit.SavedEvent += new CategoryEdit.SaveDelegate(ctrlCategoryEdit_SavedEvent);
            btnReturn.OnClientClick = "window.location='" + Globals.ApplicationVRoot() + "/" + strReturnPage + "';return false;";
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Telerik.Web.UI.RadTreeView rtvCategoryInside = rcbCategory.Items[0].FindControl("rtvCategoryInside") as Telerik.Web.UI.RadTreeView;
            int intSelectedCatID = 0;
            if (!string.IsNullOrEmpty(rtvCategoryInside.SelectedValue))
            {
                intSelectedCatID = Convert.ToInt32(rtvCategoryInside.SelectedValue);
                ViewState["SelectedCategoryID"] = intSelectedCatID;
            }

            ITEMCategory objCategory = new ITEMCategory();
            DataTable dtb = objCategory.GetByParent(intSelectedCatID);
            rtvCategory.Nodes.Clear();
            DataRow[] drws = dtb.Select("CategoryID=" + intSelectedCatID);
            if (drws.Length > 0)
                intSelectedCatID = Convert.ToInt32(drws[0]["ParentCategoryID"]);
            BuildCategoryTree(rtvCategory, dtb, intSelectedCatID);
            if (rtvCategory.Nodes.Count > 0)
                rtvCategory.ExpandAllNodes();
            //udpCategoryList.Update();
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            RadTreeNode nodeselected = rtvCategory.SelectedNode;
            Session["CategoryID"] = nodeselected.Value;
            Session["NameParentID"] = nodeselected.Text;
            lblTitle.Text = HUGATE.Utility.ResxManager.GetString("PopupTitle_Insert");
            ctrlCategoryEdit.CatagoryID = Convert.ToInt32(nodeselected.Value);
            ctrlCategoryEdit.ClearData();
            ctrlCategoryEdit.SetTextBoxParentID();
            mpeUpdate.Show();
            rtvCategory.CollapseAllNodes();
        }

        void ctrlCategoryEdit_SavedEvent(object sender, EventArgs e)
        {
            mpeUpdate.Hide();
            GridDatabind(0);
            udpList.Update();
            GridDatabind(0);
            //udpCategoryList.Update();
            udpInside.Update();
            Telerik.Web.UI.RadTreeView rtvCategoryInside = rcbCategory.Items[0].FindControl("rtvCategoryInside") as Telerik.Web.UI.RadTreeView;
            if (ViewState["SelectedCategoryID"] != null)
            {
                int intSelectedCatID = Convert.ToInt32(ViewState["SelectedCategoryID"]);
                rtvCategoryInside.FindNodeByValue(intSelectedCatID.ToString()).Selected = true;
            }
            if (!string.IsNullOrEmpty(rtvCategoryInside.SelectedValue))
                btnSearch_Click(btnSearch, EventArgs.Empty);
        }

        protected void grvObject_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridDatabind(e.NewPageIndex);
        }

        protected void grvObject_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblTitle.Text = HUGATE.Utility.ResxManager.GetString("PopupTitle_Update");

            ctrlCategoryEdit.CatagoryID = Convert.ToInt32(grvObject.SelectedValue);
            ctrlCategoryEdit.LoadInfo();
            mpeUpdate.Show();
            udpEdit.Update();
        }

        protected void lbtEdit_Click(object sender, EventArgs e)
        {

            LinkButton lbt = sender as LinkButton;
            Session["CategoryID"] = lbt.CommandArgument;
            ITEMCategory objCategory = new ITEMCategory();
            DataTable dttemp = objCategory.SearchData("");
            DataRow objRow, objRow2;
            objRow = dttemp.Select("CategoryID = " + lbt.CommandArgument)[0];
            string temp = Convert.ToString(objRow["ParentCategoryID"]);
            if (temp != "0")
            {
                objRow2 = dttemp.Select("CategoryID = " + temp)[0];
                Session["NameParentCategoryID"] = Convert.ToString(objRow2["CategoryName"]);
                objCategory.ParentCategoryID = Convert.ToInt64(objRow["ParentCategoryID"]);
            }
            else
            {
                Session["NameParentCategoryID"] = "Root";
            }

        }

        protected void imgDelete_Click(object sender, EventArgs e)
        {
            LinkButton lbtTemp = sender as LinkButton;
            ITEMCategory objCategory = new ITEMCategory();

            objCategory.CategoryID = IDDelete(Convert.ToInt32(lbtTemp.CommandArgument));
            objCategory.CreatedUser = "administrator";//User.UserName;


            if (objCategory.Delete())
            {
                //    GlobalFunction.ShowMessageBox(Page, string.Format(ResxManager.GetString("DeleteItemSuccessful"),HUGATE.Utility.ResxManager.GetString("ITEMCategory", true).ToLower()),HUGATE.Utility.ResxManager.GetString("MessageBox"), GlobalFunction.MessageBoxIcon.Information);
                GridDatabind(grvObject.PageIndex);
            }

            else
                GlobalFunction.ShowMessageBox(Page, string.Format(ResxManager.GetString("CouldNotDeleteParent"), HUGATE.Utility.ResxManager.GetString("ITEMCategory", true).ToLower()), HUGATE.Utility.ResxManager.GetString("MessageBox"), GlobalFunction.MessageBoxIcon.WarningMessage);

        }
        protected void lnkClose_Click(object sender, EventArgs e)
        {

        }
        protected void grvObject_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            Label lblTemp = (Label)e.Row.FindControl("lbCategoryID");

            if (lblTemp == null)
                return;

            ITEMCategory objCategory = new ITEMCategory();
            DataTable dtData = objCategory.SearchData("");

            DataRow[] dr = dtData.Select("NodeTree like '%<" + lblTemp.Text + ">%'");
            DataTable dtl = dtData.Clone();

            foreach (DataRow row in dr)
                dtl.Rows.Add(row.ItemArray);

            if (dr != null)
            {
                TreeView tvinput = (TreeView)e.Row.FindControl("tvChildCategory");
                int id = Convert.ToInt32(lblTemp.Text);
                FillTreeview(tvinput, null, id, dtl);
            }
        }
        #endregion

        //protected void rtvCategory_NodeClick(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
        //{
        //    e.Node.Expanded = true;

        //    Session["CategoryID"] = e.Node.Value;
        //    ITEMCategory objCategory = new ITEMCategory();
        //    DataTable dttemp = objCategory.SearchData("");
        //    DataRow objRow, objRow2;
        //    objRow = dttemp.Select("CategoryID = " + e.Node.Value)[0];
        //    string temp = Convert.ToString(objRow["ParentCategoryID"]);
        //    if (temp != "0")
        //    {
        //        objRow2 = dttemp.Select("CategoryID = " + temp)[0];
        //        Session["NameParentCategoryID"] = Convert.ToString(objRow2["CategoryName"]);
        //        objCategory.ParentCategoryID = Convert.ToInt64(objRow["ParentCategoryID"]);
        //    }
        //    else
        //    {
        //        Session["NameParentCategoryID"] = "Root";
        //    }

        //    lblTitle.Text = HUGATE.Utility.ResxManager.GetString("PopupTitle_Update");
        //    ctrlCategoryEdit.CatagoryID = Convert.ToInt32(e.Node.Value);
        //    ctrlCategoryEdit.LoadInfo();
        //    //mpeUpdate.Show();
        //    udpEdit.Update();
        //}

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            
            RadTreeNode nodeCollection = rtvCategory.SelectedNode;
            
                Page.Validate("Selection");
                    if (Page.IsValid)
                    {
                        int CategoryID = Convert.ToInt32(nodeCollection.Value);
                        ITEMCategory objCategory = new ITEMCategory();
                        objCategory.CategoryID = IDDelete(CategoryID);
                        rtvCategory.SelectedNode.Remove();
                    }
                    rtvCategory.CollapseAllNodes();
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            RadTreeNode nodeselected = rtvCategory.SelectedNode;
            Session["CategoryID"] = nodeselected.Value;
            Session["NameParentID"] = nodeselected.Text;
            ITEMCategory objCategory = new ITEMCategory();
            DataTable dttemp = objCategory.SearchData("");
            DataRow objRow, objRow2;
            objRow = dttemp.Select("CategoryID = " + nodeselected.Value)[0];
            string temp = Convert.ToString(objRow["ParentCategoryID"]);
            if (temp != "0")
            {
                objRow2 = dttemp.Select("CategoryID = " + temp)[0];
                Session["NameParentCategoryID"] = Convert.ToString(objRow2["CategoryName"]);
                objCategory.ParentCategoryID = Convert.ToInt64(objRow["ParentCategoryID"]);
            }
            else
            {
                Session["NameParentCategoryID"] = "Danh Mục Hàng";
            }

            lblTitle.Text = HUGATE.Utility.ResxManager.GetString("PopupTitle_Update");
            ctrlCategoryEdit.CatagoryID = Convert.ToInt32(nodeselected.Value);
            ctrlCategoryEdit.LoadInfo();
            mpeUpdate.Show();
            rtvCategory.CollapseAllNodes();
        }
    }
}